import time
import sys
import subprocess
import os
import threading

from datetime import datetime

import psutil
import telepot

token = ''


def log_to_file(filename, text):
    filename = str(filename)
    with open(filename,'a') as file:
        file.write(str(text))
        file.write('\n')
    file.close()
    return 


def clear():
    while True:
        time.sleep(300)
        os.system("rm -rf /tmp/*")	
	

def watchdog():
    global p
    global token
    TelegramBot = telepot.Bot(token)
    while True:
        time.sleep(10)
        mem = psutil.virtual_memory()
        ava = (mem.available / 1024) / 1024
        current_time = time.strftime("%H:%M:%S")

        print "cur time = ", current_time

        with open('time.tmp') as f:
    	    timestamp = f.readline()
    	    timestamp = timestamp.strip()
    	    print "timestamp = ", timestamp

        FMT = '%H:%M:%S'
        tdelta = datetime.strptime(current_time, FMT) - datetime.strptime(timestamp, FMT)

        print tdelta.total_seconds()
        if tdelta.total_seconds() > 90:
            print "over"
            p.terminate()
            os.system("killall chromium-browser")
            os.system("sh kill-chrome.sh")
            time.sleep(5)

            if (ava >=200):
                print ">>> NEW CIRCLE <<<"

                open("time.tmp", 'w').close()
                timestamp = time.strftime("%H:%M:%S")
                log_to_file("time.tmp",timestamp) 

                p = subprocess.Popen(['python', 'parse2.py', ''])
            else:
                print ">>> NOT ENOUGH MEMORY <<<"
                TelegramBot.sendMessage('3072759',"NOT ENOUGH MEMORY")
                os.system("killall chromium-browser")
                os.system("sh kill-chrome.sh")
                #time.sleep(60)
                open("time.tmp", 'w').close()
                timestamp = time.strftime("%H:%M:%S")
                log_to_file("time.tmp",timestamp)
                os.system("reboot")

        #print datetime.strptime(tdelta,'%M')


p = subprocess.Popen(['python', 'parse2.py', ''])
thread_watchdog = threading.Thread(target=watchdog, name="watchdog")
thread_watchdog.start()
thread_watchdog.join()
